package org.jeecg.modules.tencent.handle;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.modules.wx.entity.WxUserinfo;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.jeecg.common.util.IMJsonUtil;
import org.jeecg.common.util.enums.centent.UserStateAction;
import org.jeecg.common.util.tencent.response.IMBaseResponse;
import org.jeecg.modules.abs.TencentCallBackAbstract;
import org.jeecg.modules.tencent.enums.IMCallbackEnum;
import org.jeecg.modules.tencent.vo.UserStatusChangeVo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Optional;

import static org.jeecg.modules.tencent.util.TencentCallBackConstants.USER_STATUS;

/**
 * @author guoyh
 * @ClassName UserStatusHandle
 * @Description
 * @since 2020/9/6 02:36
 **/
@Component(value = USER_STATUS)
@Slf4j
public class UserStatusHandle extends TencentCallBackAbstract {

    @Resource
    private IWxUserinfoService wxUserinfoService;
    @Override
    public IMCallbackEnum getHandleClass() {
        return IMCallbackEnum.USER_STATUS;
    }

    @Override
    protected IMBaseResponse handle(String body) {
        log.info("用户状态变更，参数：{}",body);
        UserStatusChangeVo userStatusChangeVo = IMJsonUtil.parse(body,UserStatusChangeVo.class);
        Optional<UserStatusChangeVo.Info> optionalInfo = Optional.ofNullable(userStatusChangeVo).map(UserStatusChangeVo::getInfo);
        if (optionalInfo.isPresent()){
            String action = optionalInfo.get().getAction();
            UserStateAction userStateAction = UserStateAction.getInstance(action);
            if (Objects.nonNull(userStateAction) && !UserStateAction.Login.equals(userStateAction)){
                String userId = optionalInfo.get().getToAccount();
                WxUserinfo user = wxUserinfoService.getById(userId);
                if (Objects.nonNull(user)){
                    user.setLoginGroupId("");
                    wxUserinfoService.updateById(user);
                }
            }
        }
        return IMBaseResponse.buildSuccess();
    }
}
